<?php
/**
 * Created by yuxianjun001@icloud.com.
 * User: wuchen
 * Date: 2019/4/2
 * Time: 11:18
 */

namespace App\Services\Order;


use App\Helpers\ItemHelper;
use App\model\OrderModel\BusinessOrderModel;
use App\Services\BaseService;
use Illuminate\Support\Facades\DB;
use App\model\GoodsModel\BusinessGoodsModel;

/**
 * 商家-订货订单服务层
 * Class BusinessOrderService
 * @package App\Services\Order
 */
class BusinessOrderService extends BaseService
{
    protected $model;

    public function __construct()
    {
        $this->model = new BusinessOrderModel();
    }

    /**
     * 生成订货订单
     */
    public function create($request)
    {
        try {
            $this->model->business_id  = $request->businessId;//商家id
            $this->model->total_amount = $request->totalAmount;//订单总金额
            $this->model->order_status = 1;//订单状态，默认1
            $this->model->pay_way      = 0;//支付方式，默认0-未支付
            $this->model->order_no     = ItemHelper::createItem('DHDD');//订单号
            $this->model->goods_info   = $request->goodsInfo;//订单信息，一个json体，包含商品的信息，价格等需要冗余写入
            $res                       = $this->model->save();

            if (!empty($res)) {
                return $this->response('', '订单创建成功');
            }
            return $this->response('', '订单创建失败', 500);

        } catch (\Exception $e) {
            return $this->response($e->getMessage(), '订单创建异常', 500);
        }

    }

    /**
     * 订货订单列表
     * @param $request
     */
    public function list($request)
    {
        try {
            $dbResult = DB::table('business_order')->where('business_order.deleted_at', null);
            if (!empty($request->orderNo)) {
                $dbResult = $dbResult->where('business_order.order_no', $request->orderNo);
            }
            if (!empty($request->orderStatus)) {
                $dbResult = $dbResult->where('business_order.order_status', $request->orderStatus);
            }
            if (!empty($request->timeBegin) && !empty($request->timeEnd)) {
                $dbResult = $dbResult->whereBetween('business_order.created_at', [$request->timeBegin, $request->timeEnd]);
            }
            $dbResult = $dbResult->leftJoin('users', 'business_order.business_id', '=', 'users.id')
                ->select('business_order.*', 'users.name as business_name', 'users.phone as business_phone', 'users.address as business_address');

            return $this->response($this->model->buildPaginate($dbResult, $request), '查询成功');
        } catch (\Exception $e) {
            return $this->response($e->getMessage(), '查询异常', 500);
        }

    }

    /**
     * 订货订单详情
     * @param $request
     */
    public function info($request)
    {
        $res = $this->model->where('id', $request->id)->first();
        if (empty($res)) {
            return $this->response('', '此订货订单不存在', 404);
        }
        return $this->response($res->toArray(), '查询成功');

    }

    /**
     * 订货订单备注
     * @param $request
     */
    public function remark($request)
    {
        try {
            $res = $this->model->where('id', $request->id)->first();
            if (empty($res)) {
                return $this->response('', '此订货订单不存在', 404);
            }
            $data = [
                'remark' => $request->remark ?: '',
            ];
            $res  = $this->model->where('id', $request->id)->update($data);
            if (!empty($res)) {
                return $this->response('', '备注成功');
            }

            return $this->response('', '备注失败', 500);

        } catch (\Exception $e) {
            return $this->response($e->getMessage(), '备注异常', 500);
        }

    }

    /**
     * 订货订单关闭
     * @param $request
     */
    public function close($request)
    {
        try {
            $res = $this->model->where('id', $request->id)->first();
            if (empty($res)) {
                return $this->response('', '此订货订单不存在', 404);
            }
            $data = [
                'order_status' => 4,//订单状态，1-待支付，2-待发货，3-已发货，4-已经关闭
            ];
            $res  = $this->model->where('id', $request->id)->update($data);
            if (!empty($res)) {
                return $this->response('', '该订货订单关闭成功！');
            }

            return $this->response('', '该订货订单关闭失败!', 500);

        } catch (\Exception $e) {
            return $this->response($e->getMessage(), '该订货订单关闭异常', 500);
        }

    }

    /**
     * 订货订单确认发货
     * @param $request
     */
    public function confirm($request)
    {
        DB::beginTransaction();
        try {
            $res = $this->model->where('id', $request->id)->first();
            if (empty($res)) {
                return $this->response('', '此订货订单不存在', 404);
            }
            $data = [
                'order_status' => 3,//订单状态，1-待支付，2-待发货，3-已发货，4-已经关闭
            ];
            $res  = $this->model->where('id', $request->id)->update($data);

            $this->addToBusinessGoodsList($request);//添加商品到商家商品列表

            DB::commit();
            if (!empty($res)) {
                return $this->response('', '确认发货成功！');
            }
            return $this->response('', '确认发货失败!', 500);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->response($e->getMessage(), '确认发货异常', 500);
        }
    }


    /**
     * 增加商品到商家商品表
     * @param $request
     * @return string
     */
    public function addToBusinessGoodsList($request)
    {
        $goods = BusinessGoodsModel::where(
            ['goods_id' => $request->goodsId, 'deleted_at' => null])
            ->first();

        if (!empty($goods)) {
            $this->response('', '存在同名商品', 400);
        }

        $goodsModel           = new BusinessGoodsModel();
        $goodsModel->goods_id = $request->goodsId;
        $res                  = $goodsModel->save();

        if (!empty($res)) {
            return $this->response('', '新增商品到商家商品列表成功');

        } else {
            return $this->response('', '新增商品到商家商品列表失败', 500);
        }
    }

}